/**
 * 
 */
package com.fet.sc.filter;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import com.fet.sc.util.KeywordsFilter;


/**
 * @author Jeff  Gu
 * 
 */
public class FileKeyWordsFilter implements Filter {

	protected Log logger = LogFactory.getLog(FileKeyWordsFilter.class);
    
    
    private KeywordsFilter KeywordsFilter = new KeywordsFilter();
    
    //不檢核的url
    private static Set<String> noneRestrictedResources = new HashSet<String>();
    static {
    	noneRestrictedResources.add("index.jsp");
        noneRestrictedResources.add("login.jsp");
        noneRestrictedResources.add("top.jsp");
        noneRestrictedResources.add("top_right.jsp");
        noneRestrictedResources.add("top_right_right.jsp");
        noneRestrictedResources.add("redirect_login.jsp");
        noneRestrictedResources.add("logout.jsp");
        noneRestrictedResources.add("g007");
        noneRestrictedResources.add("g008");
        noneRestrictedResources.add("xc2_template.jsp");
        noneRestrictedResources.add("customer");
    }

    //URI 須完整符合的樣式, 符合者則截取 group 1 作為 program id
    private static String[] uriPatterns = new String[]{
         ".*?/([a-zA-Z]\\d{3}).*?\\.do"
        ,".*?/([a-zA-Z0-9_]*.jsp)"
        ,".*?/(customer).*?\\.do"
        };

    private static String methodPattern = ".*?method=(.*?)(&.*?)*?";
    
    private static String methodTypes = "doImportExcel|doQueryByExcel";
    
    
    public void init(FilterConfig filterConfig) throws ServletException {

  
    }

    
	public void destroy() {

	}

	public void doFilter(ServletRequest servletrequest,
			ServletResponse servletresponse, FilterChain filterchain)
			throws IOException, ServletException {

		String functionItemId = null;
		String methodId = null;
        try
        {
   	
        	HttpServletRequest httpservletrequest = (HttpServletRequest)servletrequest;
			String servletPath = httpservletrequest.getServletPath(); //ex:[/a005.do]			 
	        String queryString = httpservletrequest.getQueryString();//ex:[method=doQuery&orgId=1...]
            functionItemId = SecurityHelper.getProgramIdFromURI(servletPath, uriPatterns);
            methodId = SecurityHelper.getMethodFromQueryString(queryString, methodPattern);
	        
          
//          先排除特定網頁
    	if(!isNoneRestricted(functionItemId)&& null !=  methodId  && methodId.length()!=0)//排除未帶參數的查詢
    	{  
            Pattern pattern = Pattern.compile(methodTypes);

    		Matcher matcher = pattern.matcher(methodId);
    
    	   //不是特定metihd(ex:使用excel查詢)就不做	
           if (!matcher.find()){
            	filterchain.doFilter(servletrequest, servletresponse);	
			}
           	//試試看轉型httpservletrequest
           //還沒有進 org.springframework.web.servlet.DispatcherServlet 所以沒辦法轉型
        	MultipartHttpServletRequest multipartRequest= (MultipartHttpServletRequest) httpservletrequest;
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
 
			logger.error("上傳 file "+file.getOriginalFilename());
		
		
			
			//xls才要檢核
			if((file.getOriginalFilename().endsWith(".xls"))){
				//使用KeywordsFilter 過濾問題字串
				
//				需確認是否檔案資料流會被用完
				if(KeywordsFilter.checkXlscontent(file.getInputStream(),file.getOriginalFilename()))
				{	
//是否真的匯跳錯誤視窗					
					PrintWriter out	=servletresponse.getWriter();
					out.write("<script language='javascript'>alert('檔案內容含問題字串,請檢查後重新上傳');</script>");							
					return ; 
				}
			}
			
		}  
            filterchain.doFilter(servletrequest, servletresponse);
         
        }
        catch (Exception e)
        {
           
            logger.error("", e);
            servletrequest.getRequestDispatcher("/error.jsp").forward(servletrequest, servletresponse);
        }
        finally
        {
        	
        }
        

	}
    
	 private boolean isNoneRestricted(String s)
	    {
	        return noneRestrictedResources.contains(s);
	    }  
    
}
